<?php

namespace App\Http\Controllers\Home;

use App\Http\Requests\ArticleRequest;
use App\Model\Article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{

    public function __construct ()
    {
        //除了index、show方法不需要登录
        $this->middleware ( 'auth' , [ 'except' => [ 'index' , 'show' ] ] );
//        dd(1);
    }

    public function index()
    {
//        $article=Article::find(2);
//        dd($article->user->name);
        $articles=\App\Model\Article::orderBy('created_at','desc')->paginate(10);
        return view('home.article.index',compact('articles'));
    }


    public function create()
    {
        return view('home.article.create');
    }


    public function store(ArticleRequest $request)
    {
        $article=auth()->user()->article()->create($request->all());
        return redirect(route('article.show',$article))->with('success','添加成功');
    }


    public function show(Article $article)
    {
//        $isZan=$article->zan()->get()->contains(auth()->user());
//        $users=$article->zan()->get();
        return view('home.article.show',compact('article'));
    }


    public function edit(Article $article)
    {
        $this->authorize ('update',$article);
        return view('home.article.edit',compact('article'));
    }


    public function update(ArticleRequest $request, Article $article)
    {
        $this->authorize ('update',$article);
         $article->update($request->all());
        return redirect(route('article.show',$article))->with('success','更新成功');
    }


    public function destroy(Article $article)
    {
        $this->authorize ('update',$article);
        $article->delete();
        return back()->with('success','删除成功');
    }
}
